package com.txf.simple.ui.view;

import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Paint;
import android.graphics.PorterDuff;
import android.util.AttributeSet;
import android.widget.ImageView;

import com.txf.simple.R;

/**
 * 可修改 图片颜色的 ImagView
 */
public class ColorChangeImageView extends ImageView {
    Bitmap bitmap_heart;
    public ColorChangeImageView(Context context) {
        super(context);
        init();
    }

    public ColorChangeImageView(Context context, AttributeSet attrs) {
        super(context, attrs);
        init();
    }
    public ColorChangeImageView(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        init();
    }
    /**
     * 初始化需要修改的图片
     * */
    private void init() {
        bitmap_heart = BitmapFactory.decodeResource(getResources(), R.drawable.loading);
    }
    @Override
    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
        super.onMeasure(widthMeasureSpec, heightMeasureSpec);
        setMeasuredDimension(bitmap_heart.getWidth(), bitmap_heart.getHeight());
    }
    /**
     * 最终颜色
     * */
    public void setColor(int color) {
        setImageBitmap(createColor(color));
    }

    private Bitmap createColor(int color) {
        int heartWidth = bitmap_heart.getWidth();
        int heartHeight = bitmap_heart.getHeight();
        Bitmap newBitmap = Bitmap.createBitmap(heartWidth, heartHeight, Bitmap.Config.ARGB_8888);
        Canvas canvas = new Canvas(newBitmap);
        Paint paint = new Paint();
        paint.setAntiAlias(true);
        canvas.drawBitmap(bitmap_heart, 0, 0, paint);
        canvas.drawColor(color, PorterDuff.Mode.SRC_ATOP);
        canvas.setBitmap(null);
        return newBitmap;
    }
}